// CommandParser.cpp
#include "CommandParser.h"
#include <HardwareConfig.h>

CommandParser::CommandParser(uint8_t maxHandlers)
{
    this->maxHandlers = maxHandlers;
    handlers = new CommandHandler[maxHandlers];
    handlerNames = new char *[maxHandlers];
    handlerCount = 0;

    resetParser();
    waitingForInput = false;
}

CommandParser::~CommandParser()
{
    delete[] handlers;
    for (uint8_t i = 0; i < handlerCount; i++)
    {
        delete[] handlerNames[i];
    }
    delete[] handlerNames;
}

void CommandParser::update()
{
    while (Serial.available())
    {
        char c = Serial.read();
        processChar(c);
    }
}

void CommandParser::sendFlowControl(char ctrlChar)
{
    // 流程控制字符发送
}

void CommandParser::beginOutput()
{
    sendFlowControl(CTRL_S); // 暂停输入
    delay(10);               // 确保终端处理完成
}

void CommandParser::endOutput()
{
    sendFlowControl(CTRL_Q); // 恢复输入
    delay(10);
    sendRaw("\r\n" PROMPT);
}

void CommandParser::resetParser()
{
    bufferIndex = 0;
    state = STATE_NORMAL;
    inContinuation = false;
    currentToken = "";
    isNamedArg = false;
    memset(buffer, 0, sizeof(buffer));
}

void CommandParser::processChar(char c)
{
    // 跳过流程控制字符
    if (c == CTRL_S || c == CTRL_Q || c == CTRL_R)
    {
        return;
    }

    // 如果正在等待输入参数
    if (waitingForInput)
    {
        if (c == '\n' || c == '\r')
        {
            if (currentToken.length() > 0)
            {
                // 添加参数到部分命令
                if (expectedParam.startsWith("--"))
                {
                    partialCommand.namedArgs.push_back(expectedParam);
                    partialCommand.namedValues.push_back(currentToken);
                }
                else
                {
                    partialCommand.args.push_back(currentToken);
                }

                sendRaw("\r\n");
                waitingForInput = false;
                currentToken = "";
                expectedParam = "";

                // 执行部分命令
                executeCommand(partialCommand);
            }
            return;
        }
        else if (c == 0x7F || c == 0x08)
        { // 退格
            if (currentToken.length() > 0)
            {
                currentToken.remove(currentToken.length() - 1);
                sendRaw("\b \b");
            }
        }
        else if (c >= 32 && c <= 126)
        { // 可打印字符
            currentToken += c;
            sendRaw(String(c));
        }
        return;
    }

    // 正常指令解析 - 回车或换行表示命令结束
    if (c == '\n' || c == '\r')
    {
        if (bufferIndex > 0)
        {
            buffer[bufferIndex] = '\0';
            parseLine(String(buffer));
            resetParser();
        }
        else
        {
            sendRaw("\r\n" PROMPT);
        }
        return;
    }

    // 缓冲区保护
    if (bufferIndex >= MAX_CMD_LENGTH - 1)
    {
        DEBUG_PRINTLN("[ERROR] Command buffer overflow");
        resetParser();
        sendResponse("system", "error: Command too long");
        return;
    }

    // 将字符存入缓冲区
    buffer[bufferIndex++] = c;
}
// CommandParser.cpp - 在 parseLine 函数中添加位置参数支持
void CommandParser::parseLine(const String& line) {
    Command cmd;
    std::vector<String> tokens;
    String token = "";
    bool inQuote = false;
    char quoteChar = '"';
    bool inEscape = false;
    
    // 分词逻辑，正确处理引号和转义
    for (unsigned int i = 0; i < line.length(); i++) {
        char c = line[i];
        
        if (inEscape) {
            token += c;
            inEscape = false;
        } else if (c == '\\') {
            inEscape = true;
        } else if (inQuote) {
            if (c == quoteChar) {
                inQuote = false;
                if (token.length() > 0) {
                    tokens.push_back(token);
                    token = "";
                }
            } else {
                token += c;
            }
        } else {
            if (c == '"' || c == '\'') {
                inQuote = true;
                quoteChar = c;
            } else if (c == ' ' || c == '\t') {
                if (token.length() > 0) {
                    tokens.push_back(token);
                    token = "";
                }
            } else {
                token += c;
            }
        }
    }
    
    if (token.length() > 0) {
        tokens.push_back(token);
    }
    
    if (tokens.size() == 0) {
        return;
    }
    
    // 解析主命令和子命令
    String fullCmd = tokens[0];
    int underscorePos = fullCmd.indexOf('_');
    if (underscorePos != -1) {
        cmd.mainCmd = fullCmd.substring(0, underscorePos);
        cmd.subCmd = fullCmd.substring(underscorePos + 1);
    } else {
        cmd.mainCmd = fullCmd;
        cmd.subCmd = "";
    }
    
    // 命名参数解析
    String currentNamedArg = "";
    
    for (size_t i = 1; i < tokens.size(); i++) {
        String token = tokens[i];
        
        if (token.startsWith("--")) {
            // 这是命名参数
            currentNamedArg = token.substring(2); // 去掉 "--"
            
            // 检查下一个token是否是值
            if (i + 1 < tokens.size() && !tokens[i + 1].startsWith("--")) {
                // 下一个token是值
                cmd.namedArgs.push_back(currentNamedArg);
                cmd.namedValues.push_back(tokens[i + 1]);
                i++; // 跳过下一个token，因为我们已经处理了它
            } else {
                // 没有值，可能是布尔标志
                cmd.namedArgs.push_back(currentNamedArg);
                cmd.namedValues.push_back("true");
            }
            currentNamedArg = "";
        } else if (!currentNamedArg.isEmpty()) {
            // 当前token是命名参数的值
            cmd.namedArgs.push_back(currentNamedArg);
            cmd.namedValues.push_back(token);
            currentNamedArg = "";
        } else {
            // 位置参数
            cmd.args.push_back(token);
        }
    }
    
    executeCommand(cmd);
}
 
void CommandParser::executeCommand(const Command &cmd)
{
    String fullCmd = cmd.mainCmd;
    if (cmd.subCmd.length() > 0)
    {
        fullCmd += "_" + cmd.subCmd;
    }

    // 首先尝试匹配完整命令（如 "bt_start_ble"）
    for (uint8_t i = 0; i < handlerCount; i++)
    {
        if (strcmp(handlerNames[i], fullCmd.c_str()) == 0)
        {
            beginOutput();
            handlers[i](cmd);
            endOutput();
            return;
        }
    }

    // 如果没有找到完整匹配，尝试只匹配主命令（如 "bt"）
    for (uint8_t i = 0; i < handlerCount; i++)
    {
        if (strcmp(handlerNames[i], cmd.mainCmd.c_str()) == 0)
        {
            beginOutput();
            handlers[i](cmd);
            endOutput();
            return;
        }
    }

    DEBUG_PRINTLN("[DEBUG] No handler found for command: " + fullCmd);
    sendResponse("error", "Unknown command: " + cmd.mainCmd);
}

void CommandParser::registerCommand(const String &cmdName, CommandHandler handler)
{
    if (handlerCount >= maxHandlers)
    {
        DEBUG_PRINTLN("[ERROR] Cannot register '" + cmdName + "': max handlers reached");
        return;
    }

    handlerNames[handlerCount] = new char[cmdName.length() + 1];
    strcpy(handlerNames[handlerCount], cmdName.c_str());
    handlers[handlerCount] = handler;
    handlerCount++;
}

void CommandParser::sendResponse(const String &category, const String &message)
{
    sendRaw("[" + category + "] " + message + "\r\n");
}

void CommandParser::sendRaw(const String &data)
{
    Serial.print(data);
}

void CommandParser::waitForInput(const String &prompt)
{
    sendFlowControl(CTRL_R); // 等待输入
    if (prompt.length() > 0)
    {
        sendRaw(prompt + ": ");
    }
}

void CommandParser::promptForInput(const String &paramName)
{
    waitForInput("Enter " + paramName);
}

// 工具方法实现
String CommandParser::getNamedArg(const Command &cmd, const String &name, const String &defaultValue)
{
    for (size_t i = 0; i < cmd.namedArgs.size(); i++)
    {
        if (cmd.namedArgs[i] == name)
        {
            return cmd.namedValues[i];
        }
    }
    return defaultValue;
}

int CommandParser::getNamedArgInt(const Command &cmd, const String &name, int defaultValue)
{
    String value = getNamedArg(cmd, name);
    if (value.length() == 0)
        return defaultValue;
    return value.toInt();
}

bool CommandParser::getNamedArgBool(const Command &cmd, const String &name, bool defaultValue)
{
    String value = getNamedArg(cmd, name);
    if (value.length() == 0)
        return defaultValue;
    return value == "true" || value == "1" || value == "yes";
}

String CommandParser::getPositionalArg(const Command &cmd, int index, const String &defaultValue)
{
    if (index < 0 || index >= (int)cmd.args.size())
        return defaultValue;
    return cmd.args[index];
}